package com.wooophone.buyi.biz.impl;

import org.apache.ibatis.reflection.MetaClass;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.wooophone.buyi.bean.GatherImage;
import com.wooophone.buyi.biz.PinBiz;
import com.wooophone.common.util.MatcheUtil;

public class PinBizImpl implements PinBiz {

	@Override
	public GatherImage gatherImage(String url) throws ParserException {
		
		Parser parser = new Parser (url);
		
		//过滤出title标签和img标签
		NodeFilter[]  filters = new NodeFilter[3];
		filters[0] = new NodeClassFilter(MetaClass.class);
		filters[1] = new NodeClassFilter(TitleTag.class);
		filters[2] = new NodeClassFilter(ImageTag.class);
		NodeFilter filter = new OrFilter(filters);
		NodeList  list = parser.extractAllNodesThatMatch(filter);
		
		Node[] nodes = list.toNodeArray();
		
		GatherImage gatherImage=new GatherImage();
		gatherImage.setSourceUrl(url);
		
		//分解出title和img的Url
		for (Node node : nodes) {
			if(node instanceof TitleTag){
				gatherImage.setTitle(gatherImage.getTitle()+" | "+node.toPlainTextString().trim());
			}else{
				ImageTag imageTag=(ImageTag)node;
				String imageUrl=imageTag.getImageURL();
				boolean isUrl = MatcheUtil.matcheUrl(imageUrl);
				if(isUrl){
					gatherImage.getImgUrls().add(imageUrl);
				}
			}
		}
		
		return gatherImage;
	}

}
